<?php
/**
 * Created by PhpStorm.
 * User: yafex
 * Date: 2018/11/5
 * Time: 10:30
 */
class model_com extends L {

    /**
     * 描述：获取系统配置信息
     * 参数：配置标识
     * 返回值：对应配置的数组
     * 作者：Zoro.Zhu
     **/
    public static function getVsConfig($type){
        $subject = 'VS_'.$type;
        $key = md5($subject);
        if (of_base_com_kv::get($key) !== false) {
            $info = of_base_com_kv::get($key);
        } else {
            $sql = "SELECT
                `data`
            FROM `vs_config`
            WHERE `type` = '{$type}'";
            $res = L::sql($sql);
            $info = !empty($res[0]['data']) ? $res[0]['data'] : '{}';
            of_base_com_kv::set($key , $info, 86400);
        }
        $data = json_decode($info, true);
        return $data;
    }

    /**
     * 描述 : 创建文件夹
     * 参数 :
     *      dir : 需要创建的文件夹路径
     * 作者 : Zoro.Zhu
     */
    public static function mkdirs($dir) {
        if (!is_dir($dir)) {
            if (!self::mkdirs(dirname($dir))) {
                return false;
            }
            if (!mkdir($dir,0755)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 描述 : 删除目录下所有文件
     * 参数 :
     *      $path : 需要删除的文件夹路径
     * 作者 : Zoro.Zhu
     */
    public static function deldir($path) {
        //如果是目录则继续
        if (is_dir($path)) {
            //扫描一个文件夹内的所有文件夹和文件并返回数组
            $p = scandir($path);
            foreach ($p as $val) {
                //排除目录中的.和..
                if ($val != "." && $val != "..") {
                    //如果是目录则递归子目录，继续操作
                    if (is_dir($path . $val)) {
                        //子目录中操作删除文件夹和文件
                        self::deldir($path . $val . '/');
                        //目录清空后删除空文件夹
                        @rmdir($path . $val . '/');
                    } else {
                        //如果是文件直接删除
                        unlink($path . $val);
                    }
                }
            }
        }
    }

    /**
     * 描述 ：将图片base64编码
     * 参数 ：$imageFile : 图片路径
     * 作者 ：Zoro.Zhu
     **/
    public static function base64EncodeImage ($imageFile) {
        $imageInfo = getimagesize($imageFile);
        $imageData = fread(fopen($imageFile, 'r'), filesize($imageFile));
        $base64Image = 'data:' . $imageInfo['mime'] . ';base64,' . chunk_split(base64_encode($imageData));
        return $base64Image;
    }

    /**
     * 描述 : 获取账号cookie
     * 作者 : Zoro.Zhu
     */
    public static function getAccountCookie($account){
        $subject = 'Cookie_' . $account;
        $key = md5($subject);
        if (of_base_com_kv::get($key) !== false) {
            $info = of_base_com_kv::get($key);
        } else {
            $sql = "SELECT
                account,
                cookie 
            FROM
                vs_account_cookie 
            WHERE
                account = '{$account}'";
            $res = L::sql($sql);
            $info = !empty($res[0]['cookie']) ? $res[0]['cookie'] : false;
            of_base_com_kv::set($key , $info, 86400);
        }
        return $info;
    }

    /**
     * 描述 : 获取当前账号的店小秘账号
     * 作者 : Zoro.Zhu
     */
    public static function getDxmAccount(){
        $user = core_base::getUser('name');
        if($user != 'admin'){
            $where = " addName = '{$user}'";
        } else {
            $where = " 1";
        }
        $sql = "SELECT
            account 
        FROM
            `vs_account_cookie` 
        WHERE
            {$where}";
        $res = L::sql($sql);
        return array_column($res,'account');
    }

    /**
     * 描述 : 获取当前账号的平台账号
     * 作者 : Zoro.Zhu
     */
    public static function getAccount($type){
        $user = core_base::getUser('name');
//        if($user != 'admin'){
            $where = " addName = '{$user}'";
//        } else {
//            $where = " 1";
//        }
        $sql = "SELECT
            account 
        FROM
            `vs_account` 
        WHERE
            {$where} 
        AND `type` = '{$type}'";
        $res = L::sql($sql);
        return array_column($res,'account');
    }


    /**
     * 描述 : 获取cookie
     * 作者 : Zoro.Zhu
     */
    public static function getCookie($account){
        $sql = "SELECT
            cookie 
        FROM
            `vs_account_cookie` 
        WHERE
            account = '{$account}'";
        $info = L::sql($sql);
        return !empty($info[0]['cookie']) ? $info[0]['cookie'] : '';
    }

    /**
     * 描述 : 获取国家信息
     * 作者 : Zoro.Zhu
     */
    public static function getCountryCode(){
        $sql = "SELECT
            countryCode,englishName,chineseName,abbreviation
        FROM
            `country_code` 
        WHERE
            1 ";
        $info = L::sql($sql);
        $data = [];
        foreach($info as $row){
            $data[$row['countryCode']] = $row;
        }
        return $data;
    }

    /**
     * 描述 : xls 下载封装
     * 参数 ：
     *      $firstLine array 首行及数据键值 例：['name' => '中文名','user' => '用户名']
     *      $data array 下载数据 二维数组
     *      $fileName str 下载文件名
     *      $imgKey array 要下载图片的字段
     * 作者 : Smart.Chen
     */
    public static function xlsDownload($firstLine = [], $data = [], $fileName = 'download.xls', $imgKey = [])
    {
        L::open('excel');
        $objPHPExcel = new PHPExcel();
        $objActSheet = $objPHPExcel->getActiveSheet();
        //统一设置单元格样式
        $lineArr = [];
        $firstLineArr = array_keys($firstLine);
        for ($i = 0; $i < count($firstLine); $i++) {
            $y = ($i / 26);
            if ($y >= 1) {
                $y = intval($y);
                $lineArr[$firstLineArr[$i]] = chr($y + 64) . chr($i - $y * 26 + 65);
                $str = chr($y + 64) . chr($i - $y * 26 + 65);
            } else {
                $lineArr[$firstLineArr[$i]] = chr($i + 65);
                $str = chr($i + 65);
            }
            $objPHPExcel->setActiveSheetIndex(0)->getStyle($str)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER)->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $objPHPExcel->getActiveSheet()->getColumnDimension($str)->setWidth(20);
        }
        //自动换行 日志列
        $objActSheet->getStyle('S2:S' . (count($data) + 1))->getAlignment()->setWrapText(true);
        //第一行
        $first = 1;
        foreach ($firstLine as $f => $val) {
            $objActSheet->setCellValue($lineArr[$f] . $first, $val);
        }
        foreach ($data as $k => $v) {
            $k += 2;
            foreach ($v as $ke => $item) {
                if (!empty($lineArr[$ke])) {
                    if (in_array($ke, $imgKey)) {
                        if (is_file(stripslashes($item))) {
                            // 图片生成
                            $objDrawing[$k] = new PHPExcel_Worksheet_Drawing();
                            $objDrawing[$k]->setPath(stripslashes($item));
                            // 设置宽度高度
                            $objDrawing[$k]->setHeight(130);//照片高度
                            $objDrawing[$k]->setWidth(130); //照片宽度
                            /*设置图片要插入的单元格*/
                            $objDrawing[$k]->setCoordinates($lineArr[$ke] . $k, $item);
                            // 图片偏移距离
                            $objDrawing[$k]->setOffsetX(6);
                            $objDrawing[$k]->setOffsetY(6);
                            $objDrawing[$k]->setWorksheet($objPHPExcel->getActiveSheet());
                        } else {
                            $url = $item;
                            $filename = pathinfo($url, PATHINFO_BASENAME);
                            if (empty($filename)) {
                                continue;
                            }
                            if (!is_dir(ROOT_DIR . '/data/downImage')) {
                                mkdir(ROOT_DIR . '/data/downImage', 0755, true);
                            }
                            $path = ROOT_DIR . '/data/downImage/' . $filename;
                            $pathNew = ROOT_DIR . '/data/downImage/new-' . $filename;
                            if (!file_exists($pathNew)) {
                                $ch = curl_init();
                                curl_setopt($ch, CURLOPT_URL, $url);
                                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
                                $file = curl_exec($ch);
                                curl_close($ch);
                                $resource = fopen($path, 'a');
                                if ($resource !== false && $file) {
                                    fwrite($resource, $file);
                                    fclose($resource);
                                    if (file_exists($path) && is_file($path)) {
                                        $pathNew = self::imageCompression($path, $pathNew);
                                    }
                                }
                            }
                            if (file_exists($pathNew)) {
                                $objDrawing[$k] = new PHPExcel_Worksheet_Drawing();
                                $objDrawing[$k]->setPath($pathNew);
                                // 设置宽度高度
                                $objDrawing[$k]->setHeight(130);//照片高度
                                $objDrawing[$k]->setWidth(130); //照片宽度
                                /*设置图片要插入的单元格*/
                                $objDrawing[$k]->setCoordinates($lineArr[$ke] . $k, $item);
                                // 图片偏移距离
                                $objDrawing[$k]->setOffsetX(6);
                                $objDrawing[$k]->setOffsetY(6);
                                $objDrawing[$k]->setWorksheet($objPHPExcel->getActiveSheet());
                                //                unlink($path);
                            } else {
                                $objActSheet->setCellValue($lineArr[$ke] . $k, '');
                            }
                        }
                    } else {
                        $objActSheet->setCellValue($lineArr[$ke] . $k, $item);
                    }
                }
            }
            // 表格高度
            $objActSheet->getRowDimension($k)->setRowHeight(100);
        }
        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        // $objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=$fileName");
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
    }

    /**
     * 描述 : 图片压缩按比例
     * 参数 ：
     *      $oldDir 图片原始路径
     *      $newDir 压缩图片保存路径
     *      $size 压缩后尺寸 默认 200
     *      $del 是否删除原始文件
     * 作者 : Smart.Chen
     */
    public static function imageCompression($oldDir, $newDir = '', $size = 100, $del = true)
    {
        if ($oldDir == '') {
            return false;
        }
        if ($newDir == '') {
            $pathInfo = pathinfo($oldDir);
            $newName = explode('.', $pathInfo['basename']);
            $newPath = $pathInfo['dirname'];
            $newName = $newName[0];
            $newDir = $newPath . '/' . $newName . '_' . $size . '.' . $pathInfo['extension'];
        }
        if (file_exists($newDir)) {
            return $newDir;
        }
        //获取原始图片长宽及类型
        list($width, $height, $type) = getimagesize($oldDir);
        switch ($type) {
            case 1:
                $image = imagecreatefromgif($oldDir);
                break;
            case 2:
                $image = imagecreatefromjpeg($oldDir);
                break;
            case 3:
                $image = imagecreatefrompng($oldDir);
                break;
        }
        //按照尺寸等比计算长宽
        if ($width >= $size) {
            $per = $size / $width;//计算比例
            $new_width = $width * $per;
            $new_height = $height * $per;
        } else {
            $new_width = $width;
            $new_height = $height;
        }
        $image_wp = imagecreatetruecolor($new_width, $new_height);
        imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
        //保存压缩后的图片
        imagejpeg($image_wp, $newDir, 90);
        if ($del) {
            //删除原始图片
            unlink($oldDir);
        }
        return $newDir;
    }

    /**
     * 描述 : 物流属性
     * 作者 : Zoro.Zhu
     */
    public static function getLogisAttr(){
        return [
            '001' => '普货',
            '002' => '防疫普货',
            '101' => '无电池的电子产品',
            '201' => '小剪刀类',
            '202' => '螺丝刀工具类',
            '203' => '折刀类',
            '204' => '管制刀具类',
            '205' => '大剪刀类',
            '301' => '强磁性产品',
            '302' => '弱磁性产品',
            '401' => '手表类',
            '402' => '纽扣电池',
            '403' => '蓝牙、小电池产品',
            '404' => '内置电池',
            '405' => '配套电池',
            '406' => '柱状纯电池',
            '407' => '≤2600MAH的纯电池',
            '408' => '＞2600MAH的纯电池',
            '501' => '粉末类',
            '502' => '膏状类产品',
            '503' => '清洁胶产品',
            '601' => '液体类',
            '701' => '轻抛类',
            '702' => '带油按摩腰带产品',
            '801' => '易碎',
            '602' => '含酒精',
            '409' => '锂离子电池',
            '410' => '锂金属电池',
            '411' => '干电池',
            '412' => '电容',
            '905' => '形式武器的产品（JOOM用）',
            '902' => '植物（JOOM用）',
            '903' => '茶叶（JOOM用）',
            '904' => '动物毛和真人发（JOOM用）',
            '901' => '成人用品',
            '704' => '易燃易爆类产品',
            '703' => '高密度类产品',
            '206' => '电动工具类产品',
            '207' => '尖锐类产品',
            '504' => '喷雾、密封气压类产品'
        ];
    }

     public static function html2text($str){
        $str = preg_replace("/<style .*?<\\/style>/is", "", $str);
        $str = preg_replace("/<script .*?<\\/script>/is", "", $str);
        $str = preg_replace("/<br \\s*\\/>/i", "\n", $str);
        $str = preg_replace("/<\\/?p>/i", "\n", $str);
        $str = preg_replace("/<\\/?td>/i", "", $str);
        $str = preg_replace("/<\\/?div>/i", "\n", $str);
        $str = preg_replace("/<\\/?blockquote>/i", "", $str);
        $str = preg_replace("/<\\/?li>/i", "\n", $str);
        $str = preg_replace("/ /i", " ", $str);
        $str = preg_replace("/ /i", " ", $str);
        $str = preg_replace("/&/i", "&", $str);
        $str = preg_replace("/&/i", "&", $str);
        $str = preg_replace("/</i", "<", $str);
        $str = preg_replace("/</i", "<", $str);
        $str = preg_replace("/“/i", '"', $str);
        $str = preg_replace("/&ldquo/i", '"', $str);
        $str = preg_replace("/‘/i", "'", $str);
        $str = preg_replace("/&lsquo/i", "'", $str);
        $str = preg_replace("/'/i", "'", $str);
        $str = preg_replace("/&rsquo/i", "'", $str);
        $str = preg_replace("/>/i", ">", $str);
        $str = preg_replace("/>/i", ">", $str);
        $str = preg_replace("/”/i", '"', $str);
        $str = preg_replace("/&rdquo/i", '"', $str);
        $str = strip_tags($str);
        $str = html_entity_decode($str, ENT_QUOTES, "utf-8");
        $str = preg_replace("/&#.*?;/i", "", $str);
        return $str;
    }


}